import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ns_ble/flutter_ns_ble.dart';
import 'package:flutter_ns_ble_example/sync_data_page.dart';
import 'package:path_provider/path_provider.dart';

class MainPage extends StatefulWidget {
  final Peripheral peripheral;
  const MainPage({super.key, required this.peripheral});

  @override
  State<StatefulWidget> createState() {
    return _MainPageState();
  }
}

class _MainPageState extends State<MainPage> {
  Peripheral get peripheral => widget.peripheral;
  StreamSubscription? _stateSubscription;
  @override
  void initState() {
    _stateSubscription = peripheral.leadState.listen((state) {
      print("$this leadState:$state");
    });

    super.initState();
  }

  @override
  void dispose() {
    _stateSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
        actions: [
          StreamBuilder(
            stream: peripheral.state,
            builder: (context, snapshot) {
              if (snapshot.data == PeripheralState.disconnected) {
                return IconButton(
                  icon: const Icon(Icons.bluetooth),
                  onPressed: () async {
                    try {
                      bool result = await peripheral.connect();
                      print("$this connect $result");
                    } catch (e) {
                      print(e);
                    }
                  },
                );
              } else {
                return IconButton(
                  icon: const Icon(Icons.link_off),
                  onPressed: () async {
                    try {
                      bool result = await peripheral.disconnect();
                      print("$this disconnect $result");
                    } catch (e) {
                      print(e);
                    }
                  },
                );
              }
            },
          ),
        ],
      ),
      body: Center(
        child: StreamBuilder(
          stream: peripheral.state,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Text("hasError:" + snapshot.error.toString());
            }
            switch (snapshot.data) {
              case null:
              case PeripheralState.disconnected:
              case PeripheralState.connecting:
              case PeripheralState.disconnecting:
              case PeripheralState.connected:
                return Text("${snapshot.data?.name}");
              case PeripheralState.ready:
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // FutureBuilder(
                    //   future: peripheral.requestLeadState(),
                    //   builder: (context, snapshot) {
                    //     if (snapshot.hasData) {
                    //       return Text("${snapshot.data}");
                    //     } else {
                    //       return Text("Fetching lead state...");
                    //     }
                    //   },
                    // ),
                    StreamBuilder(
                      stream: peripheral.leadState,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return Text("${snapshot.data}");
                        } else {
                          return Text("Listening lead state...");
                        }
                      },
                    ),
                    StreamBuilder(
                      stream: peripheral.info,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return Text("Lead State:${snapshot.data}");
                        } else {
                          return Text("Listening lead state...");
                        }
                      },
                    ),

                    StreamBuilder(
                      stream: peripheral.ecgData,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          return Text("${snapshot.data}");
                        } else {
                          return Text("Listening ECG Data...");
                        }
                      },
                    ),
                    TextButton(
                      child: Text("Start ECG"),
                      onPressed: () async {
                        await peripheral.startECG();
                      },
                    ),
                    TextButton(
                      child: Text("Stop ECG"),
                      onPressed: () async {
                        await peripheral.stopECG();
                      },
                    ),
                    StreamBuilder(
                      stream: peripheral.dfuState,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          switch (snapshot.data?.state) {
                            case null:
                            case DFUState.idle:
                              return TextButton(
                                onPressed: () async {
                                  var dir =
                                      await getApplicationCacheDirectory();
                                  var filePath =
                                      dir.path + "/A1_1.00.28_240124.bin";
                                  await Dio().download(
                                    "http://guangzhoukangyuanai.com/root/AI_Platform/guangzhoukangyuanai/FileRoot/firmware_files/2024/01/25/A1_1.00.28_240124.bin",
                                    filePath,
                                  );
                                  await peripheral.startDFU(filePath);
                                },
                                child: Text("Start DFU 28_240124"),
                              );
                            case DFUState.canceled:
                              return Text("Canceled");
                            case DFUState.start:
                              return Text("Start");
                            case DFUState.progress:
                              return TextButton(
                                onPressed: () {
                                  peripheral.cancelDFU();
                                },
                                child: Text(
                                  "DFUProgress:${(snapshot.data)?.sentSize},${(snapshot.data)?.totalSize}",
                                ),
                              );
                            case DFUState.completed:
                              return Text(
                                "Completed:${(snapshot.data)?.stateCode},${(snapshot.data)?.errorMsg}",
                              );
                          }
                        } else {
                          return Text("Not connected");
                        }
                      },
                    ),
                    StreamBuilder(
                      stream: peripheral.dfuState,
                      builder: (context, snapshot) {
                        if (snapshot.hasData) {
                          switch (snapshot.data?.state) {
                            case null:
                            case DFUState.idle:
                              return TextButton(
                                onPressed: () async {
                                  var dir =
                                      await getApplicationCacheDirectory();
                                  var filePath =
                                      dir.path + "/A1_1.00.26_210806.bin";
                                  await Dio().download(
                                    "http://guangzhoukangyuanai.com/root/AI_Platform/guangzhoukangyuanai/FileRoot/firmware_files/2024/01/09/A1_1.00.26_231220.bin",
                                    filePath,
                                  );
                                  await peripheral.startDFU(filePath);
                                },
                                child: Text("Start DFU 26_210806"),
                              );
                            case DFUState.canceled:
                              return Text("Canceled");
                            case DFUState.start:
                              return Text("Start");
                            case DFUState.progress:
                              return TextButton(
                                onPressed: () {
                                  peripheral.cancelDFU();
                                },
                                child: Text(
                                  "DFUProgress:${(snapshot.data)?.sentSize},${(snapshot.data)?.totalSize}",
                                ),
                              );
                            case DFUState.completed:
                              return Text(
                                "Completed:${(snapshot.data)?.stateCode},${(snapshot.data)?.errorMsg}",
                              );
                          }
                        } else {
                          return Text("Not connected");
                        }
                      },
                    ),
                    if (peripheral.type == PeripheralType.b1)
                      TextButton(
                                onPressed: () {
                                  Navigator.of(context).push(
                                    MaterialPageRoute(
                                      builder: (context) {
                                        return SyncDataPage(
                                          peripheral: peripheral,
                                        );
                                      },
                                    ),
                                  );
                                },
                                child: Text(
                                  "同步数据",
                                ),
                              )
                  ],
                );
            }
          },
        ),
      ),
    );
  }
}
